<?php
// +----------------------------------------------------------------------
// | IPHP
// +----------------------------------------------------------------------
// | This is an open source and simple PHP FrameWork.
// +----------------------------------------------------------------------
// | $Id$
// +----------------------------------------------------------------------

namespace IPHP\Core;
use IPHP\Core\View;

class Controller {
    public $model; //保存一个模型
    public $get;
    public $post;
    public $server;
    public $config; //配置信息对象. 注意： 更新此对象值，并不能将新的配置写入到文件，如需写入到文件，需要使用config()函数

    public $session; //session对象

    public $view; //需要传递到模板的变量
    public $vobj; //模板引擎对象

    public function __construct() {
        //创建全局变量对象
        $this->get      = $this->_createVar('get');
        $this->post     = $this->_createVar('post');
        $this->server   = $this->_createVar('server');
        $this->config   = $this->_createVar('config');

        $this->view     = new \stdClass();
        $this->session  = new \IPHP\Core\Session();        
    }

    /**
     * 子控制器类初始化方法
     * @return [type] [description]
     */
    public function _init(){}

    /**
     * 输出模板
     * @return [type] [description]
     */
    public function display($tplFileName = "") {
        if(!$tplFileName) {
            $tplname = CONTROLLER_NAME.'/'.ACTION_NAME.TEMPLATE_SUFFIX;
            $tplFileName = VIEW_PATH.$tplname;
        } else {
            //有传入模板名
            //处理木板路径
            //TODO: 需要增加模板主题的支持
            if(strpos($tplFileName, ':')) {
                $patharr = explode(':', $tplFileName);
                if($patharr[0] == "IPHP") {
                    // 调用框架内置的模板
                    $tplFileName = IPHP_PATH.'Tpl/'.$patharr[1].TEMPLATE_SUFFIX;
                } else {
                    $tplFileName = APP_PATH.$patharr[0].'/View/'.$patharr[1].TEMPLATE_SUFFIX;
                }
            }      
        }

        //获取编译后的模板路径
        $cacheTplFile = view::getCacheTpl($tplFileName);
        $this->vobj   = new \IPHP\Core\View($tplFileName,$cacheTplFile);
        $this->vobj->checkIncludeTpl($tplFileName);
        $this->vobj->checkTpl();
        $this->vobj->display($this->view);
    }

    /**
     * 载入模型
     * @param  [type] $model_name [description]
     * @return [type]             [description]
     */
    protected function model($model_name) {
        // 查询是否有自定义模型
        if(file_exists(MODEL_PATH.$model_name.".class.php")) {
            $modelclass = "App\Model\\{$model_name}";
            $model = new $modelclass();
            $model->table($model_name);
        } else {
            $model = new \IPHP\Core\Model(); 
            $model->table($model_name);
        }

        $this->model = $model;
        return $this->model;     
    }


    /**
     * 为超全局变量创建对象
     * @param  [type] $type [description]
     * @return [type]       [description]
     */
    protected function _createVar($type) {
        $tmp = new \stdClass();
        switch ($type) {
            case 'get':
                $arr = $_GET;
                break;
            case 'post':
                $arr = $_POST;
                break;
            case 'server':
                $arr = $_SERVER;
                break;
            case 'config':
                global $config;
                $arr = $config;
                break;

            default:
                $arr = $_REQUEST;
        }

        if($arr && is_array($arr)) {
            foreach ($arr as $key => $value) {
                $tmp->$key = $value;
            }
        }
        return $tmp;
    }

    /**
     * 返回成功状态
     * @param  string $info [description]
     * @param  string $url  [description]
     * @return [type]       [description]
     */
    public function success($info="",$url="") {
        header('Content-Type:application/json; charset=utf-8');
        $data['info'] = $info;
        $data['status'] = 1;
        if($url) $data['url'] = $url;
        exit(json_encode($data));
    }

    /**
     * 返回失败状态
     * @param  string $info [description]
     * @return [type]       [description]
     */
    public function error($info="",$url="") {
        header('Content-Type:application/json; charset=utf-8');
        $data['info'] = $info;
        $data['status'] = 0;
        if($url) $data['url'] = $url;
        exit(json_encode($data));
    }


    /**
     * 分页功能
     * @return [type] [description]
     */
    public function page($m, $map="", $order="", $key="list", $perpage=20) {
        if(!$m) return false;
        // 总粗量
        $total = $m->where($map)->count('id');
        //　当前页码
        $curpage = $this->get->page ? $this->get->page : 1;
        // 总页数
        $pages = ceil($total/$perpage);
        if($curpage > $pages) $curpage = $pages;
        if($curpage < 1) $curpage = 1;

        // 起始数据
        $start = ($curpage -1) * $perpage;
        $m->select()->where($map)->limit($start.','.$perpage);
        if($order) $m->orderBy($order);
        $data = $m->fetchAll();
        if($pages > 1)
            $this->view->page = $this->pageLinkHmtl($pages,$curpage); 
        $this->view->$key = $data;
        return $data;
    }

    /**
     * 生成页码导航的html代码
     * @param  [type] $pages   [description]
     * @param  [type] $curpage [description]
     * @return [type]          [description]
     */
    protected function pageLinkHmtl($pages,$curpage) {
        //　处理当前页面url
        $url = $this->server->PHP_SELF;
        //　检查url是否带有参数
        if($this->server->QUERY_STRING) {
            $isQueryString = 1;
            // 检查页面是否带有页码参数，如有则去除
            $url = preg_replace("/&?page=\d+/iUs", '', $url);
            $url = $url.'&page=%d';
        } else {
            $isQueryString = 0;
            $url = preg_replace("#/page/\d+#", '', $url);
            $url = $url.'/page/%d';
        }

        $html = '<ul class="pagination">';
        $d = $curpage==1 ? ' class="disabled" ' : '';
        $u = sprintf($url,1);
        $html.= '<li'.$d.'><a href="'.$u.'">&laquo;</a></li>';

        //当总页数大于11时
        if($pages >11) {
            // 当前页码已经比较靠近后了
            if($curpage +5 >= $pages) {
                $i = $curpage-5-($curpage +5 - $pages);
                $u = sprintf($url,$i-1);
                $html.= '<li'.$c.'><a href="'.$u.'" target="_self">...</a></li>';
                for($i; $i <= $pages;$i++) {
                    $u = sprintf($url,$i);
                    ($i == $curpage) ? $c = ' class="active" ' : $c = '';
                    $html.= '<li'.$c.'><a href="'.$u.'" target="_self">'.$i.'</a></li>';
                }
            } else if ($curpage -5 >= 1) {
            //当前页码大于5
                $i = $curpage-5;
                if($i > 1) {
                    $u = sprintf($url,$i-1);
                    $html.= '<li'.$c.'><a href="'.$u.'" target="_self">...</a></li>';
                }

                for($i; $i <= $curpage + 5 ;$i++) {
                    if($i > $pages) break;
                    $u = sprintf($url,$i);
                    ($i == $curpage) ? $c = ' class="active" ' : $c = '';
                    $html.= '<li'.$c.'><a href="'.$u.'" target="_self">'.$i.'</a></li>';
                }
                $u = sprintf($url,$i);
                $html.= '<li'.$c.'><a href="'.$u.'" target="_self">...</a></li>';
            } else {
                $i = 1;
                for($i; $i <= $curpage + 5 + (5-$curpage) + 1;$i++) {
                    $u = sprintf($url,$i);
                    ($i == $curpage) ? $c = ' class="active" ' : $c = '';
                    $html.= '<li'.$c.'><a href="'.$u.'" target="_self">'.$i.'</a></li>';
                }
                $u = sprintf($url,$i);
                $html.= '<li'.$c.'><a href="'.$u.'" target="_self">...</a></li>';
            }
        } else {
        //总页数小于15时，　显示全部页码
            for($i=1;$i<=$pages;$i++) {
                $u = sprintf($url,$i);
                ($i == $curpage) ? $c = ' class="active" ' : $c = '';
                $html.= '<li'.$c.'><a href="'.$u.'" target="_self">'.$i.'</a></li>';
            }   
        }

        $d = $curpage==$pages ? ' class="disabled" ' : '';
        $u = sprintf($url,$pages);
        $html.= '<li><a href="'.$u.'">&raquo;</a></li>';
        $html.= '</ul>';
        return $html;
    }

    /**
     * 页面重定向
     * @param  [type]  $url  转向的网址
     * @param  integer $time 跳转等待的时间
     * @param  string  $msg  跳转提示语
     * @return [type]        [description]
     */
    public function redirect($url, $msg="", $time=0) {
        if(!preg_match("#^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$#iUs", $url)) {
            $url = url($url);
        }

        if(!$time) {
            header("location:".$url);
            return ture;
        } else {
            $this->view->url = $url;
            $this->view->time = $time;
            $this->view->msg = $msg;

            // TODO: 后续需要增加自定义提示模板的功能.
            $this->display('IPHP:redirect');            
        }
        exit;
    }

}